package com.qjc.demo.train.hashmap;

/**
 * @ClassName: MyHashMap
 * @Description:
 * @Author: qjc
 * @Date: 2022/5/1 12:47 PM
 */
public class MyHashMap {
    // 数组初始化
    ListNode[] map = new ListNode[8];
    // ListNode的个数，用于扩容
    int size;

    public void put(String key, String value) {
        if (size >= map.length * 0.75) {
            System.out.println("该扩容了");
            return;
        }
        // 计算索引，数组下标
        int index = Math.abs(key.hashCode()) % map.length;
        // 获取该下标处的ListNode
        ListNode listNode = map[index];
        if (listNode == null) {
            // 创建单链表
            ListNode listNodeNew = new ListNode();
            // 创建头结点
            Node node = new Node(key, value, null);
            // 挂载头结点
            listNodeNew.head = node;
            // 把单链表放在数组里
            map[index] = listNodeNew;
            size++;
        } else {
            // 该下标有值，Hash冲突
            listNode.addNode(key, value);
        }
    }

    public String get(String key) {
        // 计算索引，数组下标
        int index = Math.abs(key.hashCode()) % map.length;
        ListNode listNode = map[index];
        if (listNode == null) {
            return null;
        }
        return listNode.getVal(key);
    }


    public static void main(String[] args) {
        MyHashMap myHashMap = new MyHashMap();
        myHashMap.put("c1","ccccc");
        myHashMap.put("k1","kkkkk");
        myHashMap.put("m1","mmmmm");
        System.err.println(myHashMap.get("c1"));
        System.err.println(myHashMap.get("k1"));
        System.err.println(myHashMap.get("m1"));
    }
}
